<template>
  <div>
    <scroller class="scroller"
              :show-scrollbar="false">
      <vm-cell label="保单号"
               :hasTopBorder="true"
               v-if="!agencyData.agency_id">
        <input slot="title"
               placeholder="请输入保单号"
               v-model="params.insurance_order_no"
               class="input" />
      </vm-cell>

      <vm-cell label="保险公司"
               @cellClicked="agencyShow">
        <text slot="title"
              :class="['select-text', !params.agency_name && 'text-muted']">{{params.agency_name || '请选择保险公司'}}</text>
        <text class="icon text-muted"
              v-if="!isApply">&#xe69b;</text>
      </vm-cell>

      <vm-cell label="险种"
               @cellClicked="clzShow">
        <text slot="title"
              :class="['select-text', !params.insurance_class_name && 'text-muted']">{{params.insurance_class_name || '请选择险种'}}</text>
        <text class="icon text-muted"
              v-if="!isApply">&#xe69b;</text>
      </vm-cell>

      <vm-cell label="规模(数量)">
        <input slot="title"
               type="number"
               placeholder="请输入规模(数量)"
               v-model="params.scale"
               class="input"
               @input="calcFunds" />
      </vm-cell>

      <vm-cell label="保期开始时间">
        <input slot="title"
               type="date"
               placeholder="请选择保期开始时间"
               v-model="params.start_time"
               class="input" />
      </vm-cell>

      <vm-cell label="保期结束时间">
        <input slot="title"
               type="date"
               placeholder="请选择保期结束时间"
               v-model="params.end_time"
               class="input" />
      </vm-cell>

      <vm-cell label="投保人">
        <input slot="title"
               placeholder="请输入投保人"
               v-model="params.ins_person"
               class="input" />
      </vm-cell>

      <vm-cell label="联系电话">
        <input slot="title"
               placeholder="请输入投保人联系电话"
               v-model="params.mobile_no"
               class="input" />
      </vm-cell>

      <vm-cell label="被保人">
        <input slot="title"
               placeholder="请输入被保人"
               v-model="params.insured_person"
               class="input" />
      </vm-cell>

      <text class="hint-text">单位保额：{{selectClz.ins_amount || '-'}}元</text>
      <vm-cell label="保额">
        <input slot="title"
               type="number"
               placeholder="请输入保额"
               v-model="params.ins_funds"
               class="input" />
      </vm-cell>

      <text class="hint-text">保费费率：{{selectClz.ins_fee || '-'}}%</text>
      <vm-cell label="保费">
        <input slot="title"
               type="number"
               placeholder="请输入保费"
               v-model="params.ins_fee"
               class="input" />
      </vm-cell>

      <text class="hint-text">自缴比例：{{selectClz.self_fee_rate || '-'}}%</text>
      <vm-cell label="自缴金额">
        <input slot="title"
               type="number"
               placeholder="请输入自缴金额"
               v-model="params.self_fee"
               class="input" />
      </vm-cell>
    </scroller>

    <div class="bg-white py-1 border-top">
      <vm-button text="提交"
                 :btnStyle="{height: '78px'}"
                 @buttonClicked="submit"></vm-button>
    </div>

    <vm-mask height="600"
             width="560"
             :show-close="true"
             :show.sync="agencyVisible">
      <text class="p-3 border-bottom text-muted">选择保险公司</text>
      <scroller :show-scrollbar="false">
        <text v-for="(agency, index) in agencys"
              :key="index"
              :class="['list-text', selectAgencyIndex === index && 'list-text-active']"
              @click="onSelectAgency(agency, index)">{{agency.agency_name}}</text>
      </scroller>
    </vm-mask>

    <vm-mask height="600"
             width="560"
             :show-close="true"
             :show.sync="insuranceClassVisible">
      <text class="p-3 border-bottom text-muted">选择险种</text>
      <scroller>
        <text v-for="(clz, index) in insuranceClass"
              :key="index"
              :class="['list-text', selectClzIndex === index && 'list-text-active']"
              @click="onSelectClz(clz, index)">{{clz.ins_class_name}}</text>
        <text class="empty-text"
              v-if="!insuranceClass.length">该保险公司暂无可贷险种，请选择其他公司</text>
      </scroller>
    </vm-mask>

    <select-dataarea :visible.sync="selectDateVisible"></select-dataarea>

  </div>
</template>
<script>
import VmButton from '../../components/vm-button.vue'
import VmCell from '../../components/vm-cell.vue'
import VmMask from '../../components/vm-mask.vue'
import SelectDatearea from '../../components/select-datearea.vue'
import {
  STORAGE_USER,
  STORAGE_FARM,
  STORAGE_CREDIT_RELATED
} from '../../plugins/constant'

export default {
  components: { VmButton, VmCell, VmMask, SelectDatearea },
  props: {},
  data() {
    return {
      title: '申请保单',
      user: {},
      farm: {},
      related: {},
      id: '',
      params: {
        address_code: '',
        agency_id: '',
        agency_name: '',
        certify_no: '',
        certify_type: 2,
        customer_id: '',
        customer_related_id: '',
        end_time: '',
        ins_fee: '',
        ins_funds: '',
        ins_order_status: 1,
        ins_person: '',
        insurance_class_id: '',
        insurance_class_name: '',
        // insurance_order_id: '',
        insurance_order_no: '',
        insured_person: '',
        mobile_no: '',
        scale: '',
        self_fee: '',
        start_time: ''
      },
      // 
      agencys: [],
      agencyVisible: false,
      selectAgencyIndex: 0, // 用于显示选中状态
      //
      insuranceClass: [],
      insuranceClassVisible: false,
      selectClz: {}, // 用于计算
      selectClzIndex: 0,
      // 传入险种（申请）
      agencyData: {},
      isApply: false,
      // 保期选择
      selectDateVisible: false
    }
  },
  computed: {},
  watch: {},
  created() {
    this.getFarmInfo()
  },
  methods: {
    getFarmInfo() {
      this.user = this.$storage.getSync(STORAGE_USER) || {}
      this.farm = this.$storage.getSync(STORAGE_FARM) || {}
      this.related = this.$storage.getSync(STORAGE_CREDIT_RELATED) || {}
      this.params.address_code = this.farm.farmAddressCode || ''
      this.params.certify_no = this.farm.registerNo || ''
      this.params.customer_id = this.farm.id
      this.getParams()
    },
    getParams() {
      this.$router.getParams().then(res => {
        const data = res || {}

        // 是否是修改
        const applyData = data.data || {}
        if (applyData.insurance_order_id) {
          Object.keys(this.params).forEach(key => {
            this.params[key] = applyData[key] || ''
          })
          this.id = applyData.insurance_order_id || ''
          this.params.start_time = this.pureTime(this.params.start_time)
          this.params.end_time = this.pureTime(this.params.end_time)
        }

        if (!this.id) {
          // 申请或添加
          const farmer = this.farm.farmer || this.farm.contact || ''
          this.params.ins_person = farmer
          this.params.insured_person = farmer
          this.params.mobile_no = this.user.phoneNumber
          this.params.customer_related_id = this.related.customer_related_id || ''
        }

        // 是否是申请
        this.agencyData = data.agency || {}
        if (this.agencyData.agency_id) {
          this.title = '农险申请'

          this.$navigator.setNavigationInfo({
            title: this.title,
            navShow: true,
            statusBarStyle: 'LightContent'
          })

          this.isApply = true
          this.params.agency_id = this.agencyData.agency_id
          this.params.agency_name = this.agencyData.agency_name
          this.params.insurance_class_id = this.agencyData.insurance_class_id
          this.params.insurance_class_name = this.agencyData.ins_class_name
          this.selectClz = this.agencyData
        }

        this.getInsuranceAgency()
      })
    },
    pureTime(time) {
      return time ? time.substr(0, 10) : ''
    },
    getInsuranceAgency() {
      this.$api.getData({
        server: 'credit',
        table: 'datum_customer_insurance_agency'
      }).then(res => {
        this.agencys = res || []
        if (!this.id) {
          if (this.isApply) { // 申请
            this.getInsuranceClass(true)
          } else if (this.agencys.length) { // 添加
            const agency = this.agencys[0]
            this.params.agency_id = agency.agency_id
            this.params.agency_name = agency.agency_name
            this.getInsuranceClass(true)
          }
        } else {
          // 修改
          this.getInsuranceClass(true)
        }
      })
    },
    getInsuranceClass(isFirst = false) {
      this.$api.getData({
        server: 'insurance',
        table: 'insurance_class',
        params: {
          'agency_id.eq': this.params.agency_id
        }
      }).then(res => {
        this.insuranceClass = res || []
        // 第一次请求且修改不处理
        if (isFirst && this.id) { return }
        if (this.insuranceClass.length) {
          const clz = this.insuranceClass[0]
          this.params.insurance_class_id = clz.insurance_class_id
          this.params.insurance_class_name = clz.ins_class_name
        } else {
          this.params.insurance_class_id = ''
          this.params.insurance_class_name = ''
        }
      })
    },
    // 保险公司选择
    agencyShow() {
      if (!this.isApply) {
        this.agencyVisible = true
      }
    },
    onSelectAgency(agency, index) {
      this.selectAgencyIndex = index
      this.params.agency_id = agency.agency_id
      this.params.agency_name = agency.agency_name
      this.agencyVisible = false
      this.getInsuranceClass()
    },
    // 险种选择
    clzShow() {
      if (!this.isApply) {
        this.insuranceClassVisible = true
      }
    },
    onSelectClz(clz, index) {
      this.selectClz = clz
      this.calcFunds()
      this.selectClzIndex = index
      this.params.insurance_class_id = clz.insurance_class_id
      this.params.insurance_class_name = clz.ins_class_name
      this.insuranceClassVisible = false
    },
    // 计算保额、保费、自缴金额
    calcFunds() {
      if (!this.selectClz.ins_amount) { return }

      const scale = Number.parseFloat(this.params.scale) || 0
      const ia = Number.parseFloat(this.selectClz.ins_amount) || 0
      const amount = Math.round(scale * ia * 100) / 100
      this.params.ins_funds = amount

      const ifee = Number.parseFloat(this.selectClz.ins_fee) || 0
      const fe = Math.round(ifee * amount * 100) / 10000
      this.params.ins_fee = fe

      const sfee = Number.parseFloat(this.selectClz.self_fee_rate) || 0
      const sr = Math.round(sfee * fe * 100) / 10000
      this.params.self_fee = sr
    },
    // 提交按钮
    submit() {
      // 表单验证
      if (this.id && +this.params.ins_order_status === 2) {
        return this.$notice.toast({ message: '该保单由保险平台同步，不能修改！' })
      }
      if (!this.isApply && !this.params.insurance_order_no) {
        return this.$notice.toast({ message: '请输入保险单号！' })
      }
      if (!this.params.agency_id) {
        return this.$notice.toast({ message: '请选择保险机构！' })
      }
      if (!this.params.insurance_class_id) {
        return this.$notice.toast({ message: '请选择险种！' })
      }
      if (!this.params.scale) {
        return this.$notice.toast({ message: '请输入规模(数量)！' })
      }
      if (!this.params.ins_person) {
        return this.$notice.toast({ message: '请输入投保人！' })
      }
      if (!this.params.ins_funds) {
        return this.$notice.toast({ message: '请输入保额！' })
      }

      if (this.isApply || this.id) {
        this.saveData()
      } else {
        this.validateOrderNo()
      }
    },
    saveData() {
      const data = { ...this.params }
      if (!data.start_time) {
        delete data.start_time
      }
      if (!data.end_time) {
        delete data.end_time
      }
      if (this.id) {
        this.putData(data)
      } else {
        this.postData(data)
      }
    },
    validateOrderNo() {
      this.$api.getData({
        server: 'credit',
        table: 'datum_customer_insurance_order',
        params: {
          index: 1,
          size: 1,
          'customer_id.eq': this.farm.id,
          'agency_id.eq': this.params.agency_id,
          'insurance_order_no.eq': this.params.insurance_order_no
        },
        errorMsg: '提交失败，请重试！'
      }).then(res => {
        const data = res && res.data || []
        if (data.length) {
          return this.$notice.toast({ message: '单号已经存在！' })
        }
        this.saveData()
      })
    },
    putData(data) {
      this.$api.updateData({
        server: 'credit',
        table: 'datum_customer_insurance_order',
        id: this.id,
        data: data,
        errorMsg: '提交失败，请重试！'
      }).then(res => {
        this.$notice.toast({ message: '提交成功！' })
        this.$router.setBackParams({ type: 1 })
        this.$router.back()
      })
    },
    postData(data) {
      this.$api.addData({
        server: 'credit',
        table: 'datum_customer_insurance_order',
        data: data,
        errorMsg: '提交失败，请重试！'
      }).then(res => {
        this.$notice.toast({ message: '提交成功！' })
        this.$router.setBackParams({ type: 1 })
        this.$router.back()
      })
    }
  }
}
</script>
<style lang="scss" scoped>
@import "../../css/variables.scss";

.icon {
  font-family: alicon;
}
.bg-white {
  background-color: #fff;
}
.py-1 {
  padding-top: 10px;
  padding-bottom: 10px;
}
.p-2 {
  padding: 20px;
}
.p-3 {
  padding: 30px;
}
.border-top {
  border-top-width: 1px;
  border-top-color: $border-color;
}
.border-bottom {
  border-bottom-width: 1px;
  border-bottom-color: $border-color;
}
.text-muted {
  color: #999;
}

.scroller {
  width: 750px;
}
.input {
  flex: 1;
  height: 60px;
  font-size: 30px;
  tint-color: #999;
  text-align: right;
}
.select-text {
  flex: 1;
  text-align: right;
}
.list-text {
  padding: 30px;
  border-bottom-width: 1px;
  border-bottom-color: $border-color;
}
.list-text-active {
  color: $primary;
}
.empty-text {
  padding: 30px;
  color: #999;
  text-align: center;
  margin-top: 160px;
}
.hint-text {
  padding-top: 25px;
  font-size: 24px;
  color: #aaa;
  text-align: right;
  padding-right: 20px;
  padding-bottom: 5px;
}
</style>
